<?php

namespace App\Http\Middleware;

use App\Models\Token;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cookie;

class Verify
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        $token = Cookie::get('token');
        if ($token == null) return redirect('Module_C/admin');

        $user = Token::where('token', $token)
            ->where('is_admin', 1)
            ->with(['user'])
            ->first();

        $request->user = $user;

        return $next($request);
    }
}
